package com.lagou.edu.listener;

import com.alibaba.druid.pool.DruidDataSource;
import com.lagou.edu.pojo.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

/**
 * @author meng.han
 * @date 2021-09-14
 */
@Component
public class LoadCompletedListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private DruidDataSource dataSource;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        if (!"org.h2.Driver".equals(dataSource.getDriverClassName())) {
            return;
        }

        System.out.println("---------- handle refreshed event -------------");
        String accountTable = "CREATE TABLE `account` (" +
                "  `cardNo` varchar(255) NOT NULL COMMENT '银行卡号'," +
                "  `name` varchar(255) DEFAULT NULL COMMENT '用户名'," +
                "  `money` bigint(20) DEFAULT NULL COMMENT '账户余额'," +
                "  PRIMARY KEY (`cardNo`)" +
                ") ";
        jdbcTemplate.execute(accountTable);

        String insertStr = "INSERT INTO `account` VALUES ('6029621011000','李大雷',10000),('6029621011001','韩梅梅',10000)";
        jdbcTemplate.execute(insertStr);

        String sql = "select * from account where cardNo=?";
        Account account = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Account.class), "6029621011000");
        System.out.println(account);
        System.out.println("------------------init data completed ------------");
    }
}
